using System;
using System.Threading;
using System.Windows.Forms;
using Microsoft.Win32;

namespace Felbot {
    internal static class Program {
        private static bool m_Started = false;
        private static frmMain m_Main;

        public static string ApplicationFolder {
            get {
                return Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Felbot";
            }
        }

        public static frmMain MainForm {
            get {
                return m_Main;
            }
        }

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        internal static void Main(string[] args) {
            Application.SafeTopLevelCaptionFormat = "Felbot";
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            SystemEvents.SessionEnding += new SessionEndingEventHandler(SystemEvents_SessionEnding);
            Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
            if (!m_Started)
                m_Main = new frmMain(args);
            m_Main.StoreCommandLine(args);
            if (m_Started) {
                m_Main.ProcessCommandLine();
                return;
            }
            m_Started = true;
            Application.Run(m_Main);
        }

        private static void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e) {
            m_Main.Close();
        }

        private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e) {
            if (MessageBox.Show("Felbot has encountered an exception!" + Environment.NewLine +
                                "Exception: " + e.Exception.ToString() + Environment.NewLine +
                                "Do you want to continue running Felbot?",
                                "Felbot",
                                MessageBoxButtons.YesNo,
                                MessageBoxIcon.Stop,
                                MessageBoxDefaultButton.Button2)
                    == DialogResult.No) {
                Application.Exit();
            }
        }
    }
}
